<template>
  <div class="qykc_box">
    <header-comm></header-comm>
    <div class="header_sele" :style="$parent.$parent.collapsed==false?'left: 10%':'left:80px'">
      <span>客户：</span>
      <div class="sele">
        <a-input placeholder="请输入客户名称" style="width: 200px" @change="onSearch" />
        <a-icon type="search" class="search" />
      </div>
    </div>
    <!-- 表格-================= -->
    <div class="bcg">
      <div class="qykc appstyle">
        <div class="add_qy">
          <div class="add_in">
            <a
              class="drmbxz"
              style="margin-left: 26px;"
              href="http://mobile.bearing.cn/excelfile/template.xls"
            >
              <i>导入模板下载</i>
            </a>
          </div>
          <div class="add_in">
            客户名称：
            <a-select
              showSearch
              :value="khvalue"
              placeholder="客户名称"
              style="width: 200px"
              :defaultActiveFirstOption="false"
              :showArrow="false"
              :filterOption="false"
              @search="khmcSearch"
              @change="khmcChange"
              :notFoundContent="null"
            >
              <a-select-option
                v-for="(item,i) in dataSource"
                :key="i"
                :value="item.GSMC"
              >{{item.GSMC}}</a-select-option>
            </a-select>
            <!-- <a-auto-complete
              :dataSource="dataSource"
              style="width: 200px"
              placeholder="客户名称"
              @change="khmcChange"
              v-model="khvalue"
              :filterOption="khmc"
            />-->
          </div>
          <div class="add_in">
            <span>库存上传：</span>
            <div class="scexel">
              <a-upload-dragger
                name="file"
                accept=".xls, .xlsx"
                @change="Changesjdr"
                :fileList="fileList"
                :showUploadList="true"
                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                  :disabled="drload"
              
              >
                <p class="ant-upload-drag-icon">
                  <a-icon type="upload" />
                </p>
                <p class="ant-upload-text"></p>
              </a-upload-dragger>
              <a-modal v-if="sjdrmodal" title="上传成功" v-model="sjdrmodal" @ok="handleOk">
                <p>数据已载入成功,确认导入吗?</p>
              </a-modal>
            </div>
          </div>

          <div class="add_in">
            <a-button type="primary" @click="scsjexl">确认导入</a-button>
            <div class="load" v-if="drload">
              <a-spin>
                <a-icon slot="indicator" type="loading" style="font-size: 24px" spin />
              </a-spin>
            </div>

            <!-- <a-button type="primary" @click="addyblist">新增样本</a-button> -->
          </div>
        </div>

        <!-- :loading="loading" -->
        <a-table
          :pagination="pagination"
          :dataSource="data"
          :loading="loading"
          :columns="columns"
          bordered
        >
          <template v-for="titletext in []" :slot="titletext" slot-scope="text, record, index">
            <div :key="titletext"></div>
          </template>

          <template slot="operation" slot-scope="text, record, index">
            <div class="editable-row-operations">
              <span class="del">
                <!-- 客户单个---库存导入 -->
                <a-upload
                  name="file"
                  accept=".xls, .xlsx"
                  :multiple="true"
                  action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                  :headers="headers"
                  @change="Changesjdr"
                >
                  <!-- @change="kcdrChange" -->

                  <a-button @click="()=>kcdrck(record)">库存导入</a-button>
                </a-upload>
              </span>

              <span class="del" @click="()=>qykcdc(record)">库存导出</span>
              <a-popconfirm class="del" title="确定删除吗?" @confirm="() => kcdelete(record,record.key)">
                <a href="javascript:;">删除</a>
              </a-popconfirm>
              <!-- <span class="del" @click="()=>kcdelete(record,record.key)">删除</span> -->
              <span class="del" @click="()=>qyreload(record)">刷新</span>
              <span class="del" @click="()=>ckkc(record,record.key)">查看库存</span>
            </div>
          </template>
        </a-table>
      </div>
    </div>
    <a-modal v-if="kcdrmodal" title="上传成功" v-model="kcdrmodal" @ok="kcdrOk">
      <p>数据已载入成功,确认导入吗?</p>
    </a-modal>
    <!-- 表格-================= -->
    <!-- <div class="fyloading" v-if="fyflag">
      <a-spin size="large" tip="正在翻译...,过程可能需要一段时间，请耐心等待一下...">
      
      </a-spin>
    </div>-->
  </div>
</template>

<script>
import qs from "qs";
import headerComm from "../header-comm/header.vue";
import moment from "moment";

const columns = [
  {
    title: "客户ID",
    dataIndex: "bearingid"
  },
  {
    title: "客户名称",
    dataIndex: "gysmc"
  },
  {
    title: "已导入数量",
    dataIndex: "total",
    scopedSlots: { customRender: "total" }
  },
  {
    title: "导入时间",
    dataIndex: "gxsj",
    scopedSlots: { customRender: "gxsj" }
  },
  {
    title: "操作",
    dataIndex: "operation",
    scopedSlots: { customRender: "operation" },
    width: "30%"
  }
];
//上传图片
function getBase64(img, callback) {
  const reader = new FileReader();
  let file = [];
  file = reader;
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
  sessionStorage.setItem("file", reader);
}
const data = [];

export default {
  inject: ["reload"],
  data() {
    this.cacheData = data.map(item => ({ ...item }));
    return {
      data,
      columns,
      sele: "",
      serchvalue: "",
      pagination: {
        defaultPageSize: 10,
        showTotal: total => `共 ${total} 条数据`,
        total: 0
      },
      loading: true,
      drload: false,
      datakh: [],
      dataSource: [],
      datakhId: "",
      khvalue: "",
      //库存上传-----------------
      fileList: [
        {
          uid: "-1",
          name: ".xls/.xlsx",
          status: "done",
          url: "javascript:;"
        }
      ],
      uploading: false,
      exelUrl: "", //exel表格的baes64格式路径
      khexelUrl: "", //exel表格的baes64格式路径

      exflage: false, //exel表格
      sjdrmodal: false,
      kcdrmodal: false,

      xlshz: "", //上传的exel表格的后缀名
      //库存上传-----------------
      indicator: <a-icon type="loading" style="font-size: 24px" spin />,
      // fyflag: false,
      headers: {
        authorization: "authorization-text"
      }
    };
  },
  filters: {
    formatDate: function(value) {
      return moment(value).format("YYYY-MM-DD");
    }
  },
  components: {
    headerComm
  },
  // if(value=='中文'){
  //   this.cnshow='1'
  // }
  //  if(value=='英文'){
  //   this.enshow='1'
  // }
  //  if(value=='德文'){
  //   this.dwshow='1'
  // }
  //  if(value=='日文'){
  //   this.jashow='1'
  // }
  // if(value=='俄文'){
  //   this.rushow='1'
  // }
  methods: {
    //库存导入
    // kcdrChange(info) {
    //   if (info.file.status !== "uploading") {
    //     console.log(info.file, info.fileList);
    //   }
    //   if (info.file.status === "done") {
    //     this.$message.success(`${info.file.name} file uploaded successfully`);
    //   } else if (info.file.status === "error") {
    //     this.$message.error(`${info.file.name} file upload failed.`);
    //   }
    // },

    //搜索框
    onSearch(e) {
      this.serchvalue = e.target.value;
      //  this.cacheData = this.data.map(item => ({
      //         ...item
      //       }));
      console.log(this.serchvalue)
      let data1=[]
     data1= this.cacheData
    //  let data3=this.cacheData
    //  data2=this.data
          console.log(data1)
    let data2=[]
      for(var i=0;i<data1.length;i++){        	
      	if(data1[i].gysmc.indexOf(this.serchvalue)>-1 || data1[i].bearingid.indexOf(this.serchvalue)>-1){
         data2.push(data1[i]);
         
        }
      }
      
        this.data=data2
        console.log('-----------data',this.cacheData)

    },
    //客户名称
    getkhmc(value) {
      this.axios
        .post("yangben/SelectYbGsmc.php", qs.stringify({ gsmc: value }))
        .then(res => {
          console.log(res);

          if (res.data.code == 303) {
            this.dataSource = res.data.result;
            if (res.data.result.length == 0) {
              this.dataSource = [];
            }
          }
        });
    },

    //客户名称查询
    khmcChange(value) {
      this.khvalue = value;
      for (var i = 0; i < this.dataSource.length; i++) {
        if (this.khvalue == this.dataSource[i].GSMC) {
          this.datakhId = this.dataSource[i].SQDWID;
        }
      }
      if (this.khvalue == "") {
        this.datakhId = "";
      }
    },
    khmcSearch(value) {
      this.getkhmc(value);
    },
    khmc(input, option) {
      return (
        option.componentOptions.children[0].text
          .toUpperCase()
          .indexOf(input.toUpperCase()) >= 0
      );
    },

    //下拉搜索框
    handleChange(value) {
      console.log(`selected ${value}`);
    },
    handleBlur() {
      console.log("blur");
    },
    handleFocus() {
      console.log("focus");
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },

    //表格
    handleChangelist(pagination, khmc) {
      // const newData = [...this.data]
      // const target = newData.filter(item => key === item.key)[0]
      this.axios
        .post(
          "kucun/GetBusinessKc.php",
          qs.stringify({
            gysmc: khmc,
            page: pagination.current,
            pageSize: pagination.defaultPageSize
          })
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 303) {
            this.data = res.data.result;
            this.pagination.total = Number(res.data.result.total);
            this.loading = false;
            this.cacheData = this.data.map(item => ({
              ...item
            }));
            for (var i = 0; i < res.data.result.length; i++) {
              this.data[i].key = i;
            }
          } else {
            this.data = [];
          }
        });
      // if (target) {
      //   target[column] = value
      // this.data=newData
      // }
    },

    //删除客户列表
    kcdelete(value, key) {
      console.log(value);
      const dataSource = [...this.data];
      this.data = dataSource.filter(item => item.key !== key);
      this.axios
        .post(
          "kucun/DeleteBusinessKc.php",
          qs.stringify({ sqdwid: value.bearingid })
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 303) {
            this.$notification["success"]({
              message: "成功",
              description: res.data.msg
            });
          } else {
            this.$notification["error"]({
              message: "失败",
              description: res.data.msg
            });
          }
        });
    },
    kcdrck(data) {
      console.log(data.bearingid);
      this.datakhId = data.bearingid;
    },
    //数据导入--文件上传
    scsjexl() {
      if (this.datakhId != ""&&this.exelUrl!='') {
        this.loading = true;
        this.drload = true;

        this.axios
          .post( 
            "kucun/PullBusinessKc.php",
            qs.stringify({
              sqdwid: this.datakhId,
              fileBase: this.exelUrl,
              fileSuffix: this.xlshz
            })
          )
          .then(res => {
            console.log(res);
            if (res.data.code == 303) {
              this.loading = false;
              this.drload = false;

              this.$notification["success"]({
                message: "成功",
                description: res.data.msg
              });
              (this.datakhId = ""),
                (this.khvalue = ""),
                (this.exelUrl = ""),
                (this.fileList[0].name = ".xls/.xlsx");
              this.$store.commit("getSampleDetail");
            } else {
              this.drload = false;
              this.$notification["error"]({
                message: "失败",
                description: res.data.msg
              });
            }
          });
      } else if(this.datakhId == ""){
        
        this.$notification["error"]({
          message: "失败",
          description: "客户名称不能为空"
        });

        return;
      }else{
         this.$notification["error"]({
          message: "失败",
          description: "上传文件不能为空"
        });
      }
    },
    // 客户新增---库存导入

    Changesjdr(info) {
     
      let fileList = [...info.fileList];
      const status = info.file.status;

      fileList = fileList.slice(-1);
      //上传中....
      if (status !== "uploading") {
      }
      //上传后....
      if (status === "done") {
        getBase64(info.file.originFileObj, xlxurl => {
          this.exelUrl = xlxurl;
          console.log(this.exelUrl);
          this.loading = false;
          this.file = info.file.originFileObj;
        });
        this.sjdrmodal = true;
      } else if (status === "error") {
        this.$message.error(`${info.file.name} 上传失败.`);
      }
      fileList = fileList.map(file => {
        if (file.response) {
        }
        return file;
      });

      this.fileList = fileList;
      if (this.fileList == "") {
        this.exelUrl = "";
      }
      let name = this.fileList[0].name;
      var i = name.indexOf(".");
      var data = name.substring(i + 1, name.length);
      this.xlshz = data;
      console.log(data);
     
    },

    // 客户新增--库存导入
    handleOk(e) {
      this.scsjexl();
      this.sjdrmodal = false;
      console.log("新增");
    },
    // // 客户单个--库存导入
    // kcdrOk(e) {
    //   // this.scsjexl();
    //   this.kcdrmodal = false;
    //   console.log("客户上传");
    // }
    //导出
    qykcdc(data) {
      this.datakhId = data.bearingid;
      console.log(this.datakhId);
      this.axios
        .post(
          "kucun/PushBusinessKc.php",
          qs.stringify({ sqdwid: this.datakhId })
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 303) {
            this.$notification["success"]({
              message: "成功",
              description: res.data.msg
            });
            location.href = res.data.result;
          } else {
            this.$notification["error"]({
              message: "失败",
              description: res.data.msg
            });
          }
        });
    },

    //刷新页面
    qyreload(value) {
      // this.reload();
      console.log(moment(new Date()).format("YYYY-MM-DD"));
      console.log(value);
      value.gxsj = moment(new Date()).format("YYYY-MM-DD");
      this.axios
        .post(
          "kucun/RefreshKcTime.php",
          qs.stringify({ sqdwid: value.bearingid })
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 303) {
            this.$notification["success"]({
              message: "更新成功",
              description: res.data.msg,
              duration: 1.5
            });
          } else {
            this.$notification["error"]({
              message: "更新失败",
              description: res.data.msg,
              duration: 1.5
            });
          }
        });
    },
    //查看库存
    ckkc(value, key) {
      console.log(value.gysmc);
      console.log(value.bearingid);
      this.$store.state.sqdwid = value.bearingid;
      this.$store.state.gysmc = value.gysmc;
      this.$router.push("/kcgl");
    }
  },
computed: {
    filter(){
            // this.serchvalue = e.target.value;

             return this.data.filter(value=>!this.serchvalue||value.gysmc.indexOf(this.serchvalue)>-1)  
             console.log('---------')

    }
  },
  created() {
    this.handleChangelist(this.pagination);
    this.getkhmc();
  }
};
</script>

<style lang='less' >
.qykc_box {
  .header_sele {
    position: absolute;
    top: 55px;
    left: 200px;
    z-index: 999;
    text-align: right !important;
    width: 90% !important;
    background-color: #fff;
    box-shadow: 5px 5px 5px #ccc;
    // height: 50px;
    padding: 10px 20px;
    .sele {
      position: relative;
      display: inline-block;
      i {
        position: absolute;
        top: 10px;
        right: 8px;
      }
    }
  }
  .qykc {
    width: 80%;
    position: absolute;
    top: 128px;
    // left: 250px;

    .ant-table-thead {
      background-color: #ccc !important;
    }
    .ant-table-tbody {
      background: #fff !important;
    }
  }
  // .fybtn {
  //   width: 50px;
  //   vertical-align: middle;
  //   margin-left: 10px;
  //   margin-right: 10px;
  // }
  .add_qy {
    width: 100%;
    text-align: right;
    height: 55px;
    background-color: #fff;
    margin: 0px 0 11px 0;
    .ant-input {
      display: inline-block !important;
      width: 200px;
      height: 30px !important;
      font-size: 14px;
    }
    .add_in {
      position: relative;
      display: inline-block;
      text-align: left;
      margin: 0 10px;
      .load {
        position: absolute;
        background: rgba(255, 255, 255, 0.5);
        top: 0;
        right: 0;
        width: 100%;
        height: 50px;
        .ant-spin-spinning {
          position: relative;
          top: 8px;
          left: 35px;
        }
      }
      .drmbxz {
        color: #000;
        text-decoration: underline;
      }
      .ant-btn {
        height: 40px;
        padding: 0 20px;
      }
      .ant-upload-list {
        position: absolute;
        top: 0;
        left: 28px;
        .ant-upload-list-item {
          width: 130px !important;
        }
      }
      .scexel {
        position: relative;
        top: 13px;
        left: 14px;
        width: 157px !important;
        height: 36px;
        display: inline-block;
        border: 0 !important;
        // box-shadow: -3px 1px 6px #ccc;
        .ant-upload.ant-upload-drag {
          border: 0 !important;
          background-color: #fff;
          width: 20% !important;
          font-size: 25px !important;
        }
        .ant-upload {
          padding: 0px 0 !important;
        }
        .ant-upload-drag-icon {
          margin: 0 !important;
          display: inline-block !important;
          .anticon-upload {
            font-size: 25px !important;
            vertical-align: middle !important;
            margin-right: 10px;
            color: #999 !important;
          }
        }
        .ant-upload-text {
          display: inline-block !important;
        }
        .dr {
          position: absolute;
          top: 0;
          right: -92px;
          height: 51px;
        }
        .ant-upload.ant-upload-drag .ant-upload {
          padding: 0px 0 !important;
        }
      }
    }
  }
  .ant-table-wrapper {
    background: #fff !important;
  }
  .fyloading {
    position: absolute;
    width: 90% !important;
    border: 1px solid #91d5ff;
    // background: rgba(255, 255, 255, 0.5);
    padding: 30px;
    height: 800px !important;
    z-index: 999999 !important;
    top: 108px;
    left: 201px;
    // opacity: .5!important;
    .ant-spin-blur {
      opacity: 1 !important;
    }
    .ant-spin-text {
      font-size: 18px !important;
    }
    // .spin-content{
    //   color: #000;
    //   font-size: 16px!important;
    //   top: 100px!important;
    // }
  }
  .ant-spin-nested-loading > div > .ant-spin {
    top: 100px !important;
  }
  .del {
    padding-right: 15px;
    color: #40a9ff;
    cursor: pointer;
    .ant-upload-list {
      display: none !important;
    }
    .ant-btn {
      background: transparent !important ;
      border: 0 !important;
      color: #40a9ff !important;
    }
  }
}
</style>
